package com.cyp.livelog.config;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @description 认证过滤器
 */
public class AuthFilter implements Filter {

  @Override
  public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
      throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) servletRequest;
    System.out.println(req.getRequestURI());
    Object isLogin = req.getSession().getAttribute("isLogin");
    if (isLogin != null) {
      // 把请求传回过滤链: 放行
      filterChain.doFilter(servletRequest, servletResponse);
    } else {
      HttpServletResponse resp = (HttpServletResponse) servletResponse;
      req.setAttribute("message", "<b style='color:red;'>您还未登录！please login！</b>");
      req.getRequestDispatcher("/login.jsp").forward(req, resp);
    }
  }

  @Override
  public void init(FilterConfig filterConfig) throws ServletException {
    // 获取初始化参数
    String auth = filterConfig.getInitParameter("Auth");
    System.out.println(auth);//认证过滤器
  }

  @Override
  public void destroy() {
    /* 在 Filter 实例被 Web 容器从服务移除之前调用 */
  }
}
